package com.an.pay.controller;

import com.an.pay.annotation.WxPayNotify;
import com.an.pay.config.WxPayConfig;
import com.an.pay.enums.OrderStatus;
import com.an.pay.enums.PayType;
import com.an.pay.service.OrderInfoService;
import com.an.pay.vo.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.an.pay.entity.OrderInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/wx-pay")
@Slf4j
@Api(tags = "微信支付接口管理")
@CrossOrigin
public class WxPayController {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private WxPayConfig wxPayConfig;


    @ApiOperation("测试")
    @GetMapping("/test")
    public String test(){
        log.info("test执行=======");
        return "hello world";
    }

    @ApiOperation("微信支付下单")
    @PostMapping("/native/{productId}")
    public R nativePay(@PathVariable Long productId) throws Exception {
        Map<String,String> map = orderInfoService.pay(productId, PayType.WXPAY.getType());
        return R.ok().setData(map);
    }

    @ApiOperation("微信支付异步回调")
    @PostMapping("/native/notify")
    @WxPayNotify
    public void WxPayNotify(HttpServletRequest request, HttpServletResponse response,String data){
        // 这里的传入data就是 微信支付成功回调的数据
        log.info("微信支付成功返回数据data=={}",data);
        // 根据传回的数据，可以拿到订单号（out_trade_no）,根据订单号修改订单状态
        Gson gson = new Gson();
        HashMap<String,String> hashMap = gson.fromJson(data, HashMap.class);
        String orderNo = hashMap.get("out_trade_no");//订单号
        // 根据订单号修改订单状态
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderStatus(OrderStatus.SUCCESS.getType());
        orderInfoService.update(orderInfo,new QueryWrapper<OrderInfo>().eq("order_no",orderNo));
        // 记录支付成功的日志
    }



}
